package com.yabushan.activiti.service;

import java.util.ArrayList;
import java.util.List;

import com.yabushan.activiti.domain.HistoryTaskInfo;
import com.yabushan.activiti.domain.NextStepAndUser;
import com.yabushan.activiti.util.Constant;
import com.yabushan.activiti.util.Utils;
import com.yabushan.system.domain.ServiceStepConf;
import com.yabushan.system.domain.UumUserinfo;
import com.yabushan.system.service.IServiceStepConfService;
import com.yabushan.system.service.ISysUserService;
import com.yabushan.system.service.IUumUserinfoService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Service
public class VacationServiceImpl implements  VacationService{

	@Autowired
	private HistoryQueryService historyQueryService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private EngineService engineService;
	@Autowired
	private workflowUtilService workflowUtilService;
	@Autowired
	private VariablesService variablesService;
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	@Autowired
	private IServiceStepConfService serviceStepConfService;
	@Autowired
	private  IUumUserinfoService uumUserinfoService;

	@Override
	public List<HistoryTaskInfo> getAllHistoryStep(String processInstanceId, boolean isFinish, Integer firstResult, Integer maxResults) {
		List<HistoryTaskInfo> result =new ArrayList<HistoryTaskInfo>();
		HistoryTaskInfo historyTaskInfo=null;
		//获取所有历史任务
		List<HistoricTaskInstance> list=historyQueryService.getHistoricTaskInstances(processInstanceId, isFinish, firstResult, maxResults);
				//flowEngineService.getHistoricProcessInstanceByProcessDefId(processDefId);
		if(list!=null && list.size()>0){
			//遍历所有历史任务
			for (HistoricTaskInstance historicTaskInstance : list) {
				historyTaskInfo=new HistoryTaskInfo();
				historyTaskInfo.setHistoricTaskInstance(historicTaskInstance);
				if(historicTaskInstance.getEndTime()!=null){
					//封装流程变量
				List<HistoricVariableInstance> historicVariableInstances=historyQueryService.getHistoricVariableInstancesByTaskId(historicTaskInstance.getId());
					for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
						if(historicVariableInstance.getVariableName().equals(Constant.STEP_INFO)){
							historyTaskInfo.setInfo(historicVariableInstance.getValue()+"");
						}
					}
					//封装批注信息
					List<Comment> comments=commentService.getCommentByTaskId(historicTaskInstance.getId());
					if(comments!=null && comments.size()>0){
							historyTaskInfo.setTaskComment(comments);
					}else{
						historyTaskInfo.setTaskComment(null);
					}

				}else{
					historyTaskInfo.setInfo("");
					historyTaskInfo.setTaskComment(null);
				}

				result.add(historyTaskInfo);
			}
		}
		return result;
	}



	@Override
	public NextStepAndUser getFirstUser(String processKey, String userId, String empType, String processDefId, ProcessDefinitionEntity pd) {
		return null;
	}

	@Override
	public NextStepAndUser getFirstUser(String processDefinitionKey, String userId, String empType, String businessKey) {
		//根据流程key获取流程节点
		ServiceStepConf serviceStepConf=new ServiceStepConf();
		serviceStepConf.setProcdefId(processDefinitionKey);
		NextStepAndUser nextStepAndUser=new NextStepAndUser();
		List<ServiceStepConf> serviceStepConfs = serviceStepConfService.selectServiceStepConfList(serviceStepConf);
		//获取当前处理人所在组织
		UumUserinfo uumUserinfo = new UumUserinfo();
		uumUserinfo.setLoginId(userId);
		List<UumUserinfo> uumUserinfos1 = uumUserinfoService.selectUumUserinfoList(uumUserinfo);
		for (int i=0;i<serviceStepConfs.size();i++){
			ServiceStepConf step =serviceStepConfs.get(i);
			if(empType.equals(step.getStepName())){
				//判断该节点的审批类型
				if(("RY").equals(step.getDealType())){
					//具体到人
					nextStepAndUser.setNextUserId(step.getDealUserName());
					nextStepAndUser.setNextStep(step.getStepName());
				}else if("SJ".equals(step.getDealType())){
					//直接上级
					nextStepAndUser.setNextUserId(step.getDealUserName());
					nextStepAndUser.setNextStep(step.getStepName());

				}else if("JS".equals(step.getDealType())){
					//按角色
					//根据角色ID获取该角色人员
					nextStepAndUser.setNextUserId(step.getDealUserName());
					nextStepAndUser.setNextStep(step.getStepName());
				}else if("LCJS".equals(step.getDealType())){
					//按流程角色
					 uumUserinfo=new UumUserinfo();
					 if(uumUserinfos1.size()>0){
						 uumUserinfo.setCompanyId(uumUserinfos1.get(0).getCompanyId());
					 }
					uumUserinfo.setEmployeeClass(step.getDealRoleId());
					List<UumUserinfo> uumUserinfos = uumUserinfoService.selectUumUserinfoList(uumUserinfo);
					StringBuffer accountBuf = new StringBuffer();
					StringBuffer deptInfoBuf = new StringBuffer();
					for (UumUserinfo user : uumUserinfos){
						accountBuf.append(user.getLoginId()).append(",");
						String dept=user.getDepartmentName()==null?"":"/"+user.getDepartmentName();
						deptInfoBuf.append(user.getRegionName()+"/"+user.getCompanyName()+dept).append(",");
					}
					nextStepAndUser.setNextUserId(accountBuf.toString().substring(0,accountBuf.length()-1));
					nextStepAndUser.setNextStep(step.getStepName());
					nextStepAndUser.setNextUserName(deptInfoBuf.toString().substring(0,deptInfoBuf.length()-1));
				}
				break;
			}
		}
		return nextStepAndUser;
	}


	@Override
	public String getRequestUserId(String taskId) {
		//获取流程发起人
		String requestUser =variablesService.getVariablesByTaskId(Constant.REQUEST_USER, taskId, false).toString();
		return requestUser;
	}


	/**
	 *
	 * @param list List<ActivityImpl>
	 * @param nodeId 用户节点ID
	 * @param isJumpStep 标识是否跳环节，1：是
	 * @return
	 */
	public NextStepAndUser getNextStepAndUserByNodeId(List<ActivityImpl> list,String nodeId,String isJumpStep){
		NextStepAndUser nextStepAndUser2 = new NextStepAndUser();
		for (ActivityImpl act1 : list) {
    			if(nodeId.equals(act1.getId())){//公司总经理审批
    				nextStepAndUser2.setNextStep(act1.getProperty("name").toString());
    				nextStepAndUser2.setJumpStep(isJumpStep);//是否跳过步骤，1：是
    				return nextStepAndUser2;
    			}
    	}
		return null;
	}

}
